package com.doan.covua;


import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doan.covua.gamelogic.ChessController;
import com.doan.covua.gamelogic.Move;
import com.doan.covua.gamelogic.MoveGen;
import com.doan.covua.gamelogic.Piece;
import com.doan.covua.gamelogic.Position;
import com.doan.covua.gamelogic.TextIO;


/**
 * This is the main Activity that displays the current chat session.
 */
public class Chess2PActivity extends Activity implements OnClickListener, GUIInterface {
    // Debugging
    private static final String   TAG                    = "Chess2PActivity";
    private static final boolean  D                      = true;

    // Define for menu
    private final int             MENU_RECONNECT         = 0;
    private final int             MENU_NEWGAME           = 1;
    private final int             MENU_OPTION            = 2;
    private final int             MENU_MAINMENU          = 3;
    private final int             MENU_HELP              = 4;
    private final int             MENU_EXIT              = 5;

    // Define event of dialog
    private final int             EVENT_EXIT             = 0;
    private final int             EVENT_GOMAINMENU       = 1;
    private final int             EVENT_REQUESTNEWGAME   = 2;

    // Message types sent from the BluetoothChessService Handler
    public static final int       MESSAGE_STATE_CHANGE   = 1;
    public static final int       MESSAGE_READ           = 2;
    public static final int       MESSAGE_WRITE          = 3;
    public static final int       MESSAGE_DEVICE_NAME    = 4;
    public static final int       MESSAGE_TOAST          = 5;

    // Key names received from the BluetoothChessService Handler
    public static final String    DEVICE_NAME            = "device_name";
    public static final String    TOAST                  = "toast";

    // Intent request codes
    private static final int      REQUEST_CONNECT_DEVICE = 1;
    private static final int      REQUEST_ENABLE_BT      = 2;

    private static final int      PROMOTE_DIALOG         = 0;
    private static String         gameState              = "";

    // Layout Views
    private Button                m_CreateBlutooth;
    private Button                m_ConnectBluetooth;
    private Button                m_ButtonPlay2;
    private Button                m_ButtonBack2;

    private ImageButton           m_PlayAsWhite;
    private ImageButton           m_PlayAsBlack;
    private TextView              m_BluetoothStatus;

    private Dialog                dialog;

    // Name of the connected device
    private String                mConnectedDeviceName   = null;
    // String buffer for outgoing messages
    private StringBuffer          mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter      mBluetoothAdapter      = null;
    // Member object for the chess services
    private BluetoothChessService mChessService          = null;

    private SoundManager          m_SoundManager;

    private ChessController       chessCtrl;

    public static boolean         isPlayAsWhite          = true;

    private int                   current_state          = 0;

    private boolean               isChoosedPlayAs        = false;

    private boolean               isRivalReadyToPlay     = false;

    public static final int       pieceImage1[]          = { 0, R.drawable.wk_alt, R.drawable.wq_alt, R.drawable.wr_alt, R.drawable.wb_alt,
            R.drawable.wn_alt, R.drawable.wp_alt, R.drawable.bk_alt, R.drawable.bq_alt, R.drawable.br_alt, R.drawable.bb_alt, R.drawable.bn_alt,
            R.drawable.bp_alt                           };
    public static final int       pieceImage2[]          = { 0, R.drawable.wk, R.drawable.wq, R.drawable.wr, R.drawable.wb, R.drawable.wn,
            R.drawable.wp, R.drawable.bk, R.drawable.bq, R.drawable.br, R.drawable.bb, R.drawable.bn, R.drawable.bp };
    public static final int       pieceImage3[]          = { 0, R.drawable.wk3, R.drawable.wq3, R.drawable.wr3, R.drawable.wb3, R.drawable.wn3,
            R.drawable.wp3, R.drawable.bk3, R.drawable.bq3, R.drawable.br3, R.drawable.bb3, R.drawable.bn3, R.drawable.bp3 };

    // piece index of m_Taken Array.
    private int                   pieceIndex1            = 0;
    private int                   pieceIndex2            = 0;

    private boolean               s_isSfxOn;
    private int                   s_BoardSelected;
    private int                   s_PieceSelected;

    // In game define
    ChessBoard                    m_ChessBoard;
    TextView                      m_Name2;                                                                                   // m_Clock1,
                                                                                                                              // m_Clock2;
    ImageView                     m_Check1, m_Check2, m_ThinkingAnim;
    // Button m_Undo;
    AnimationDrawable             anim;
    LinearLayout                  m_Info1, m_Info2;
    ImageView                     m_Taken1[], m_Taken2[];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (D) {
            Log.e(TAG, "+++ ON CREATE +++");
        }
        // get info from ChessActivity
        Bundle getInfo = this.getIntent().getExtras();
        if (getInfo != null) {
            s_isSfxOn = getInfo.getBoolean("isSound", false);
            s_BoardSelected = getInfo.getInt("BoardSelected", 2);
            s_PieceSelected = getInfo.getInt("PieceSelected", 1);
        }

        setContentView(R.layout.newgameoptions_twoplayer);

        m_CreateBlutooth = (Button) findViewById(R.id.create_discoverable);
        m_ConnectBluetooth = (Button) findViewById(R.id.connect_device);
        m_ButtonPlay2 = (Button) findViewById(R.id.btn_play2);
        m_ButtonBack2 = (Button) findViewById(R.id.btn_back2);
        m_BluetoothStatus = (TextView) findViewById(R.id.bluetooth_status);

        m_PlayAsWhite = (ImageButton) findViewById(R.id.play_as_white2);
        m_PlayAsBlack = (ImageButton) findViewById(R.id.play_as_black2);

        m_CreateBlutooth.setOnClickListener(this);
        m_ConnectBluetooth.setOnClickListener(this);
        m_ButtonPlay2.setOnClickListener(this);
        m_ButtonBack2.setOnClickListener(this);

        m_PlayAsWhite.setOnClickListener(this);
        m_PlayAsBlack.setOnClickListener(this);

        m_PlayAsWhite.setAlpha(128);
        m_PlayAsBlack.setAlpha(128);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            // Go to main menu
            goToMainMenu();
        }

        initSound();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D) {
            Log.e(TAG, "++ ON START ++");
        }

        // If BT is not on, request that it be enabled.
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChessService == null) {
                // Initialize the BluetoothChessService to perform bluetooth
                // connections
                mChessService = new BluetoothChessService(this, mHandler);
                // Initialize the buffer for outgoing messages
                mOutStringBuffer = new StringBuffer("");
            }
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D) {
            Log.e(TAG, "+ ON RESUME +");
        }

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity
        // returns.
        if (mChessService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't
            // started already
            if (mChessService.getState() == BluetoothChessService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChessService.start();
            }
        }
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if (D) {
            Log.e(TAG, "- ON PAUSE -");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (D) {
            Log.e(TAG, "-- ON STOP --");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chess services
        if (mChessService != null) {
            mChessService.stop();
        }
        if (D) {
            Log.e(TAG, "--- ON DESTROY ---");
        }
    }

    private void ensureDiscoverable() {
        if (D) {
            Log.d(TAG, "ensure discoverable");
        }
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * 
     * @param message A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
            showCustomDialogOk("Connect to be lose");
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChessService to write
            byte[] send = message.getBytes();
            mChessService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
        }
    }

    // The Handler that gets information back from the BluetoothChessService
    private final Handler mHandler = new Handler() {
                                       @Override
                                       public void handleMessage(Message msg) {
                                           switch (msg.what) {
                                           case MESSAGE_STATE_CHANGE:
                                               if (D) {
                                                   Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                                               }
                                               switch (msg.arg1) {
                                               case BluetoothChessService.STATE_CONNECTED:
                                                   // Toast.makeText(Chess2PActivity.this,
                                                   // "Connected!!!",
                                                   // Toast.LENGTH_SHORT).show();
                                                   // mConversationArrayAdapter.clear();
                                                   break;
                                               case BluetoothChessService.STATE_CONNECTING:
                                                   m_BluetoothStatus.setText("Status: Connecting...");
                                                   break;
                                               case BluetoothChessService.STATE_LISTEN:
                                               case BluetoothChessService.STATE_NONE:
                                                   // Toast.makeText(Chess2PActivity.this,
                                                   // "not connect",
                                                   // Toast.LENGTH_SHORT).show();
                                                   m_BluetoothStatus.setText("Status: Not connected");
                                                   break;
                                               }
                                               break;
                                           case MESSAGE_WRITE:
                                               // byte[] writeBuf = (byte[])
                                               // msg.obj;
                                               // construct a string from the
                                               // buffer
                                               // String writeMessage = new
                                               // String(writeBuf);
                                               // mConversationArrayAdapter.add("Me:  "
                                               // + writeMessage);
                                               // if (isRivalReadyToPlay) {
                                               // updateBoardState();
                                               // }
                                               break;
                                           case MESSAGE_READ:
                                               byte[] readBuf = (byte[]) msg.obj;
                                               // construct a string from the
                                               // valid bytes in the buffer
                                               String readMessage = new String(readBuf, 0, msg.arg1);

                                               if (readMessage.equals("")) {
                                                   return;
                                               }
                                               if (current_state == 0) {
                                                   if (!readMessage.equals("readytoplay")) {
                                                       isPlayAsWhite = !Boolean.parseBoolean(readMessage);
                                                   }
                                                   if (isPlayAsWhite) {
                                                       m_PlayAsBlack.setAlpha(128);
                                                       m_PlayAsWhite.setAlpha(255);
                                                       isChoosedPlayAs = true;
                                                   } else {
                                                       m_PlayAsBlack.setAlpha(255);
                                                       isChoosedPlayAs = true;
                                                       m_PlayAsWhite.setAlpha(128);
                                                   }
                                               }
                                               if (!isRivalReadyToPlay) {
                                                   if (readMessage.equals("readytoplay")) {
                                                       isRivalReadyToPlay = true;
                                                   }
                                               } else {
                                                   if (readMessage.equals("newgame")) {
                                                       // newGame();
                                                       showCustomDialogYesno("Rival request new game!", EVENT_REQUESTNEWGAME);
                                                       return;
                                                   }
                                                   if (readMessage.equals("yesnewgame")) {
                                                       // reset capture piece
                                                       for (int i = 0; i < pieceIndex1; i++) {
                                                           m_Taken1[i].setImageResource(0);
                                                       }
                                                       for (int i = 0; i < pieceIndex2; i++) {
                                                           m_Taken2[i].setImageResource(0);
                                                       }
                                                       pieceIndex1 = 0;
                                                       pieceIndex2 = 0;
                                                       newGame();
                                                       return;
                                                   }
                                                   if (readMessage.equals("nonewgame")) {
                                                       showCustomDialogOk("Rival not alow new game!");
                                                       return;
                                                   }
                                                   if (readMessage.equals("exit")) {
                                                       showCustomDialogExit("Rival exit game, you will go to main menu!");
                                                       return;
                                                   }
                                                   stopThinkingAnim();

                                                   Position pos = chessCtrl.currPos();
                                                   Move m = TextIO.stringToMove(pos, readMessage);

                                                   // get current pos befor move
                                                   pos = new Position(chessCtrl.currPos());
                                                   chessCtrl.makeHumanMove(m);
                                                   updateBoardState();
                                                   // if (Position.squarePromo != -1) {
                                                   // pos.setPiece(Position.squarePromo, Piece.EMPTY);
                                                   // Position.squarePromo = -1;
                                                   // }
                                                   if (chessCtrl.getDoMove()) {
                                                       // draw last move
                                                       ChessBoard.setLastMove(m, true);

                                                       // Check status
                                                       updateCheckStatus(chessCtrl.currPos());

                                                       // draw captured piece
                                                       drawCapturedPiece(pos, m);
                                                   }
                                               }

                                               // Toast.makeText(getApplicationContext(),
                                               // "receive a move: " +
                                               // readMessage,
                                               // Toast.LENGTH_SHORT).show();
                                               break;
                                           case MESSAGE_DEVICE_NAME:
                                               // save the connected device's
                                               // name
                                               mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                                               m_BluetoothStatus.setText("Status: Connected to " + mConnectedDeviceName);
                                               break;
                                           case MESSAGE_TOAST:
                                               Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                                               break;
                                           }
                                       }
                                   };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (D) {
            Log.d(TAG, "onActivityResult " + resultCode);
        }
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChessService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Initialize the BluetoothChatService to perform bluetooth
                // connections
                mChessService = new BluetoothChessService(this, mHandler);
                // Initialize the buffer for outgoing messages
                mOutStringBuffer = new StringBuffer("");
            } else {
                // User did not enable Bluetooth or an error occured
                if (D) {
                    Log.d(TAG, "BT not enabled");
                }
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                // Go to main menu
                goToMainMenu();
            }
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.create_discoverable:
            if (isRivalReadyToPlay) {
                showCustomDialogOk("Rival is ready to play!");
                return;
            }
            ensureDiscoverable();
            break;
        case R.id.connect_device:
            if (isRivalReadyToPlay) {
                showCustomDialogOk("Rival is ready to play!");
                return;
            }
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            break;
        case R.id.btn_play2:
            if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
                // Toast.makeText(this, "Not connected to a device",
                // Toast.LENGTH_SHORT).show();
                showCustomDialogOk("Not connected to a device. Please connect befor play.");
            } else {
                if (D) {
                    Log.v(TAG, "Vao Chess board two player");
                }
                if (!isChoosedPlayAs) {
                    // Toast.makeText(this, "Please chose one color to play!",
                    // Toast.LENGTH_SHORT).show();
                    showCustomDialogOk("Please chose one color to play!");
                    return;
                }
                sendMessage("readytoplay");
                current_state = 1;
                initUI();
                if (!isPlayAsWhite) {
                    m_ChessBoard.setFlipped(true);
                }
                chessCtrl = new ChessController(Chess2PActivity.this, null);
                chessCtrl.newGame(new GameMode(GameMode.TWO_PLAYERS), false);
                chessCtrl.startGame(isPlayAsWhite);
                // Initialize the buffer for outgoing messages
                mOutStringBuffer = new StringBuffer("");
                updateBoardState();
            }
            break;
        case R.id.btn_back2:
            goToMainMenu();
            break;
        case R.id.play_as_white2:
            if (isRivalReadyToPlay) {
                showCustomDialogOk("Rival is ready to play!");
                return;
            }
            if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
                showCustomDialogOk("Not connected!");
            } else {
                ((ImageButton) v).setAlpha(255);
                m_PlayAsBlack.setAlpha(128);
                isPlayAsWhite = true;
                isChoosedPlayAs = true;
                sendMessage("true");
            }
            break;
        case R.id.play_as_black2:
            if (isRivalReadyToPlay) {
                showCustomDialogOk("Rival is ready to play!");
                return;
            }
            if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
                showCustomDialogOk("Not connected!");
            } else {
                ((ImageButton) v).setAlpha(255);
                m_PlayAsWhite.setAlpha(128);
                isPlayAsWhite = false;
                isChoosedPlayAs = true;
                sendMessage("false");
            }
            break;
        }
        // play sound select
        if (s_isSfxOn) {
            m_SoundManager.playSound(SoundManager.SOUND_SELECT);
        }
    }

    public void initUI() {
        setContentView(R.layout.ingame_singlemode);
        m_ChessBoard = (ChessBoard) findViewById(R.id.chess);
        m_Name2 = (TextView) findViewById(R.id.Name2);
        // m_Clock1 = (TextView) findViewById(R.id.Clock1);
        // m_Clock2 = (TextView) findViewById(R.id.Clock2);
        m_Check1 = (ImageView) findViewById(R.id.isCheck1);
        m_Check2 = (ImageView) findViewById(R.id.isCheck2);
        m_ThinkingAnim = (ImageView) findViewById(R.id.isThinking);
        // m_Undo = (Button) findViewById(R.id.ButtonUndo);
        m_Info1 = (LinearLayout) findViewById(R.id.Info1);
        m_Info2 = (LinearLayout) findViewById(R.id.Info2);

        findViewTaken();

        m_ChessBoard.setFocusable(true);
        m_ChessBoard.requestFocus();
        m_ChessBoard.setClickable(true);
        m_Name2.setFocusable(false);
        // m_Clock1.setFocusable(false);
        // m_Clock2.setFocusable(false);
        m_Check1.setFocusable(false);
        m_Check2.setFocusable(false);
        m_ThinkingAnim.setFocusable(false);

        m_ChessBoard.setOnClickListener(this);
        // m_Undo.setOnClickListener(this);

        m_ThinkingAnim.setImageResource(R.drawable.src_thinking_anim);
        m_ThinkingAnim.setVisibility(View.INVISIBLE);

        anim = (AnimationDrawable) m_ThinkingAnim.getDrawable();

        if (mConnectedDeviceName != null) {
            m_Name2.setText(mConnectedDeviceName);
        }

        final GestureDetector gd = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
            private float scrollX = 0;
            private float scrollY = 0;

            @Override
            public boolean onDown(MotionEvent e) {
                scrollX = 0;
                scrollY = 0;
                return false;
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                m_ChessBoard.cancelLongPress();
                handleClick(e);
                return true;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                if (e.getAction() == MotionEvent.ACTION_UP) {
                    handleClick(e);
                }
                return true;
            }

            private final void handleClick(MotionEvent e) {
                if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
                    showCustomDialogOk("Lose connect...");
                    return;
                }
                if (!myTurn()) {
                    return;
                }
                if (!isRivalReadyToPlay) {
                    showCustomDialogOk("Rival is not ready! Please wait...");
                    return;
                }
                if (chessCtrl.humansTurn()) {
                    if (D) {
                        Log.v(TAG, "handle click");
                    }
                    int sq = m_ChessBoard.eventToSquare(e);
                    Move m = m_ChessBoard.mousePressed(sq);
                    if (m != null) {
                        if (D) {
                            Log.v(TAG, "Make move when m != null");
                        }
                        // get current pos befor move
                        Position pos = new Position(chessCtrl.currPos());
                        chessCtrl.makeHumanMove(m);
                        // send move
                        if (chessCtrl.getDoMove()) {
                            sendMessage(chessCtrl.getStringToMove());
                            // draw last move
                            ChessBoard.setLastMove(m, true);

                            // Check status
                            updateCheckStatus(chessCtrl.currPos());

                            // show thinking anim
                            startThinkingAnim();
                            drawCapturedPiece(pos, m);
                        }
                        updateBoardState();
                    } else {
                        m_ChessBoard.setLegalMoveofSquare(chessCtrl.legalMoveOfSquare(sq));
                    }
                }
            }
        });
        m_ChessBoard.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                return gd.onTouchEvent(event);
            }
        });
    }

    public void setPosition(Position pos, String variantInfo, List<Move> variantMoves) {
        m_ChessBoard.setPosition(pos);

    }

    public void setSelection(int sq) {
        m_ChessBoard.setSelection(sq);

    }

    public void setAnimMove(Position sourcePos, Move move, boolean forward) {
        if (/* animateMoves && */(move != null)) {
            m_ChessBoard.setAnimMove(sourcePos, move, forward);
        }

    }

    // return my turn in two player
    private boolean myTurn() {
        return !(chessCtrl.currPos().whiteMove ^ isPlayAsWhite);
    }

    // start anim thinking
    private void startThinkingAnim() {
        if (m_ThinkingAnim != null) {
            m_ThinkingAnim.setVisibility(View.VISIBLE);
            if (anim != null) {
                anim.stop();
                anim.start();
            }
        }
    }

    // stop anim thinking
    private void stopThinkingAnim() {
        if (m_ThinkingAnim != null) {
            if (anim != null) {
                anim.stop();
                m_ThinkingAnim.setVisibility(View.INVISIBLE);
            }
        }
    }

    private void updateBoardState() {
        // update UI state bar of myturn
        if (m_Info1 != null && m_Info2 != null) {
            if (myTurn()) {
                m_Info1.setBackgroundDrawable(null);
                m_Info2.setBackgroundResource(R.drawable.player_info_overlay);
            } else {
                m_Info2.setBackgroundDrawable(null);
                m_Info1.setBackgroundResource(R.drawable.player_info_overlay);
            }
        }
    }

    private void findViewTaken() {
        m_Taken1 = new ImageView[16];
        m_Taken1[0] = (ImageView) findViewById(R.id.Taken1_1);
        m_Taken1[1] = (ImageView) findViewById(R.id.Taken1_2);
        m_Taken1[2] = (ImageView) findViewById(R.id.Taken1_3);
        m_Taken1[3] = (ImageView) findViewById(R.id.Taken1_4);
        m_Taken1[4] = (ImageView) findViewById(R.id.Taken1_5);
        m_Taken1[5] = (ImageView) findViewById(R.id.Taken1_6);
        m_Taken1[6] = (ImageView) findViewById(R.id.Taken1_7);
        m_Taken1[7] = (ImageView) findViewById(R.id.Taken1_8);
        m_Taken1[8] = (ImageView) findViewById(R.id.Taken1_9);
        m_Taken1[9] = (ImageView) findViewById(R.id.Taken1_10);
        m_Taken1[10] = (ImageView) findViewById(R.id.Taken1_11);
        m_Taken1[11] = (ImageView) findViewById(R.id.Taken1_12);
        m_Taken1[12] = (ImageView) findViewById(R.id.Taken1_13);
        m_Taken1[13] = (ImageView) findViewById(R.id.Taken1_14);
        m_Taken1[14] = (ImageView) findViewById(R.id.Taken1_15);
        m_Taken1[15] = (ImageView) findViewById(R.id.Taken1_16);

        m_Taken2 = new ImageView[16];
        m_Taken2[0] = (ImageView) findViewById(R.id.Taken2_1);
        m_Taken2[1] = (ImageView) findViewById(R.id.Taken2_2);
        m_Taken2[2] = (ImageView) findViewById(R.id.Taken2_3);
        m_Taken2[3] = (ImageView) findViewById(R.id.Taken2_4);
        m_Taken2[4] = (ImageView) findViewById(R.id.Taken2_5);
        m_Taken2[5] = (ImageView) findViewById(R.id.Taken2_6);
        m_Taken2[6] = (ImageView) findViewById(R.id.Taken2_7);
        m_Taken2[7] = (ImageView) findViewById(R.id.Taken2_8);
        m_Taken2[8] = (ImageView) findViewById(R.id.Taken2_9);
        m_Taken2[9] = (ImageView) findViewById(R.id.Taken2_10);
        m_Taken2[10] = (ImageView) findViewById(R.id.Taken2_11);
        m_Taken2[11] = (ImageView) findViewById(R.id.Taken2_12);
        m_Taken2[12] = (ImageView) findViewById(R.id.Taken2_13);
        m_Taken2[13] = (ImageView) findViewById(R.id.Taken2_14);
        m_Taken2[14] = (ImageView) findViewById(R.id.Taken2_15);
        m_Taken2[15] = (ImageView) findViewById(R.id.Taken2_16);
    }

    // draw capture piece
    private void drawCapturedPiece(Position pos, Move m) {
        if (TextIO.isCapture(pos, m)) {
            int piece = pos.getPiece(m.to);
            switch (s_PieceSelected) {
            case 1:
                if (isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(pieceImage1[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(pieceImage1[piece]);
                }
                break;
            case 2:
                if (isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(pieceImage2[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(pieceImage2[piece]);
                }
                break;
            case 3:
                if (isPlayAsWhite ^ Piece.isWhite(piece)) {
                    m_Taken1[pieceIndex1++].setImageResource(pieceImage3[piece]);
                } else {
                    m_Taken2[pieceIndex2++].setImageResource(pieceImage3[piece]);
                }
                break;
            }
        }
    }

    // Go to main menu
    private void goToMainMenu() {
        Bundle isBackToMainmenu = new Bundle();
        isBackToMainmenu.putBoolean("isBackToMainmenu", true);
        isBackToMainmenu.putBoolean("isSound", s_isSfxOn);
        Intent menuIntent = new Intent(Chess2PActivity.this, ChessActivity.class);
        menuIntent.putExtras(isBackToMainmenu);
        startActivity(menuIntent);
        Chess2PActivity.this.finish();
    }

    // check and draw CHECK status
    private void updateCheckStatus(Position pos) {
        if (MoveGen.inCheck(pos)) {
            if (myTurn()) {
                m_Check1.setVisibility(View.VISIBLE);
            } else {
                m_Check2.setVisibility(View.VISIBLE);
            }
        } else {
            m_Check1.setVisibility(View.INVISIBLE);
            m_Check2.setVisibility(View.INVISIBLE);
        }
    }

    // show custom dialog exit
    private void showCustomDialogYesno(String text, final int event) {
        dialog = new Dialog(Chess2PActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.dialog_yesno);
        dialog.setCancelable(false);
        dialog.show();
        TextView tv = (TextView) dialog.findViewById(R.id.dialog_yesno_text);
        tv.setText(text);
        Button btyes = (Button) dialog.findViewById(R.id.dialog_yes_button);
        btyes.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                switch (event) {
                case EVENT_EXIT:
                    sendMessage("exit");
                    Chess2PActivity.this.finish();
                    break;
                case EVENT_GOMAINMENU:
                    sendMessage("exit");
                    goToMainMenu();
                    break;
                case EVENT_REQUESTNEWGAME:
                    // reset capture piece
                    for (int i = 0; i < pieceIndex1; i++) {
                        m_Taken1[i].setImageResource(0);
                    }
                    for (int i = 0; i < pieceIndex2; i++) {
                        m_Taken2[i].setImageResource(0);
                    }
                    pieceIndex1 = 0;
                    pieceIndex2 = 0;
                    updateBoardState();
                    updateCheckStatus(chessCtrl.currPos());
                    newGame();
                    sendMessage("yesnewgame");
                    dialog.dismiss();
                    break;
                }
            }
        });
        Button btno = (Button) dialog.findViewById(R.id.dialog_no_button);
        btno.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
                if (event == EVENT_REQUESTNEWGAME) {
                    sendMessage("nonewgame");
                }
            }
        });
    }

    // show custom dialog ok
    private void showCustomDialogOk(String text) {
        dialog = new Dialog(Chess2PActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.dialog_ok);
        dialog.setCancelable(false);
        dialog.show();
        TextView tv = (TextView) dialog.findViewById(R.id.dialog_ok_text);
        tv.setText(text);
        Button bt = (Button) dialog.findViewById(R.id.dialog_ok_button);
        bt.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void showCustomDialogExit(String text) {
        dialog = new Dialog(Chess2PActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.dialog_ok);
        dialog.setCancelable(false);
        dialog.show();
        TextView tv = (TextView) dialog.findViewById(R.id.dialog_ok_text);
        tv.setText(text);
        Button bt = (Button) dialog.findViewById(R.id.dialog_ok_button);
        bt.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                goToMainMenu();
            }
        });
    }

    // show dialog help
    private void showCustomDialogHelp() {
        dialog = new Dialog(Chess2PActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.help);
        dialog.setCancelable(false);
        dialog.show();
        Button btnBack = (Button) dialog.findViewById(R.id.help_back);
        btnBack.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Button btnRules = (Button) dialog.findViewById(R.id.help_rules);
        btnRules.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.setContentView(R.layout.gamerules);
                Button btnRulesBack = (Button) dialog.findViewById(R.id.rules_back);
                btnRulesBack.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    // show dialog options
    private void showCustomDialogOptions() {
        dialog = new Dialog(Chess2PActivity.this, R.style.PlaqueTheme);
        dialog.setContentView(R.layout.options);
        dialog.setCancelable(false);
        dialog.show();
        final ImageButton m_Board1 = (ImageButton) dialog.findViewById(R.id.Board1);
        final ImageButton m_Board2 = (ImageButton) dialog.findViewById(R.id.Board2);
        final ImageButton m_Board3 = (ImageButton) dialog.findViewById(R.id.Board3);
        final ImageButton m_Piece1 = (ImageButton) dialog.findViewById(R.id.Piece1);
        final ImageButton m_Piece2 = (ImageButton) dialog.findViewById(R.id.Piece2);
        final ImageButton m_Piece3 = (ImageButton) dialog.findViewById(R.id.Piece3);
        final CheckBox m_SoundOn = (CheckBox) dialog.findViewById(R.id.sound_selection);
        Button m_OptionsBack = (Button) dialog.findViewById(R.id.options_back);
        m_Board1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board1.setAlpha(255);
                m_Board2.setAlpha(128);
                m_Board3.setAlpha(128);
                s_BoardSelected = 1;
            }
        });
        m_Board2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board2.setAlpha(255);
                m_Board1.setAlpha(128);
                m_Board3.setAlpha(128);
                s_BoardSelected = 2;
            }
        });
        m_Board3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Board3.setAlpha(255);
                m_Board1.setAlpha(128);
                m_Board2.setAlpha(128);
                s_BoardSelected = 3;
            }
        });
        m_Piece1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece1.setAlpha(255);
                m_Piece2.setAlpha(128);
                m_Piece3.setAlpha(128);
                s_PieceSelected = 1;
            }
        });
        m_Piece2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece2.setAlpha(255);
                m_Piece1.setAlpha(128);
                m_Piece3.setAlpha(128);
                s_PieceSelected = 2;
            }
        });
        m_Piece3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                m_Piece3.setAlpha(255);
                m_Piece1.setAlpha(128);
                m_Piece2.setAlpha(128);
                s_PieceSelected = 3;
            }
        });
        m_SoundOn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (m_SoundOn.isChecked()) {
                    s_isSfxOn = true;
                } else {
                    s_isSfxOn = false;
                }
            }
        });
        m_OptionsBack.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
                m_ChessBoard.setBoardAndPiece(s_BoardSelected, s_PieceSelected);
            }
        });

        switch (s_BoardSelected) {
        case 1:
            // m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 2:
            m_Board1.setAlpha(128);
            // m_Board2.setAlpha(128);
            m_Board3.setAlpha(128);
            break;
        case 3:
            m_Board1.setAlpha(128);
            m_Board2.setAlpha(128);
            // m_Board3.setAlpha(128);
            break;
        }

        switch (s_PieceSelected) {
        case 1:
            // m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 2:
            m_Piece1.setAlpha(128);
            // m_Piece2.setAlpha(128);
            m_Piece3.setAlpha(128);
            break;
        case 3:
            m_Piece1.setAlpha(128);
            m_Piece2.setAlpha(128);
            // m_Piece3.setAlpha(128);
            break;
        }

        if (s_isSfxOn) {
            m_SoundOn.setChecked(true);
        }

    }

    // init menu
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (current_state == 1) {
            menu.add(0, MENU_RECONNECT, 0, "Reconnect").setIcon(R.drawable.ic_menu_reconnect);
            menu.add(0, MENU_NEWGAME, 0, "New game").setIcon(R.drawable.ic_menu_newgame);
            menu.add(0, MENU_OPTION, 0, "Options").setIcon(R.drawable.ic_menu_option);
            menu.add(0, MENU_MAINMENU, 0, "Main menu").setIcon(R.drawable.ic_menu_mainmenu);
            menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
            menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    // manage select menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_RECONNECT:
            if (mChessService.getState() != BluetoothChessService.STATE_CONNECTED) {
                // goToConnectDevice();
                mChessService.start();
                Intent serverIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);

                // if (current_address != null) {
                // mChessService.start();
                // // Get the BLuetoothDevice object
                // BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(current_address);
                // // Attempt to connect to the device
                // mChessService.connect(device);
                // }
            } else {
                showCustomDialogOk("Connected!");
            }
            return true;
        case MENU_NEWGAME:
            sendMessage("newgame");
            // newGame();
            return true;
        case MENU_OPTION:
            showCustomDialogOptions();
            return true;
        case MENU_MAINMENU:
            showCustomDialogYesno("Are you sure?", EVENT_GOMAINMENU);
            return true;
        case MENU_HELP:
            showCustomDialogHelp();
            return true;
        case MENU_EXIT:
            showCustomDialogYesno("Do you want to exit?", EVENT_EXIT);
            return true;
        }
        return false;
    }

    private void newGame() {
        // current_state = 1;
        // initUI();
        // if (!isPlayAsWhite) {
        // m_ChessBoard.setFlipped(true);
        // }
        chessCtrl = new ChessController(Chess2PActivity.this, null);
        chessCtrl.newGame(new GameMode(GameMode.TWO_PLAYERS), false);
        chessCtrl.startGame(isPlayAsWhite);
        stopThinkingAnim();
        // Initialize the buffer for outgoing messages
        // mOutStringBuffer = new StringBuffer("");
        // updateBoardState();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (D) {
                Log.v(TAG, "BACK button is pressed!");
            }
        }
        return false;
    }

    public void setStatusString(String str) {
        // TODO Auto-generated method stub
        gameState = str;
    }

    public void requestPromotePiece() {
        showDialog(PROMOTE_DIALOG);
    }

    public void runOnUIThread(Runnable runnable) {
        // TODO Auto-generated method stub

    }

    public void showGameResult() {
        // TODO Auto-generated method stub
        showCustomDialogOk(gameState);
    }

    public void initSound() {
        m_SoundManager = new SoundManager();
        m_SoundManager.initSounds(getBaseContext());
        m_SoundManager.addSound(SoundManager.SOUND_SELECT, R.raw.select);
        m_SoundManager.addSound(SoundManager.SOUND_CHECK, R.raw.voicecheckmate);
        m_SoundManager.addSound(SoundManager.SOUND_PICEDROP, R.raw.piecedrop);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case PROMOTE_DIALOG:
            final CharSequence[] items = { getString(R.string.queen), getString(R.string.rook), getString(R.string.bishop),
                    getString(R.string.knight) };
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.promote_pawn_to);
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    // TODO Auto-generated method stub
                    Position pos1 = new Position(chessCtrl.currPos());
                    chessCtrl.reportPromotePiece(item);
                    Position pos = chessCtrl.currPos();
                    Move m = chessCtrl.getMovePromo();
                    sendMessage(TextIO.moveToString(pos, m, false));
                    // draw last move
                    ChessBoard.setLastMove(m, true);
                    // Check status
                    updateCheckStatus(pos);
                    // show thinking anim
                    startThinkingAnim();
                    drawCapturedPiece(pos1, m);
                    updateBoardState();
                }
            });
            AlertDialog alert = builder.create();
            return alert;

        }
        return null;
    }

}
